package org.hb0712.discovery.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.hb0712.discovery.pojo.Album;
import org.hb0712.discovery.pojo.Image;
import org.hb0712.discovery.pojo.Label;
import org.hb0712.discovery.service.AlbumService;
import org.hb0712.discovery.service.ImageService;
import org.hb0712.discovery.service.LabelService;
import org.hb0712.discovery.service.impl.FileConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ImageController {
	private Logger logger = LoggerFactory.getLogger(ImageController.class);
	
	@Autowired
	private ImageService imageService;
	@Autowired
	private AlbumService albumService;
	@Autowired
	private LabelService labelService;
	
	//@ResponseBody
	@RequestMapping("/image/list")
	public String list(Map<String,Object> model,
			String date, String album, String label, String keyword,
			HttpServletRequest request) throws UnsupportedEncodingException {
		
		List<Image> list = null;
		Set<String> dates = null;
		if(StringUtils.isNotEmpty(date)) {logger.info(date);
			list = imageService.list(date);
			dates = getDates(list);
		} else if (StringUtils.isNotEmpty(album)) {logger.info(album);
			Album obj_album = albumService.getAlbum(album);
			if (obj_album!=null) {
				list = obj_album.getImages();
			}
		} else if (StringUtils.isNotEmpty(label)) {logger.info(label);
			Label obj_label = labelService.getLabel(label);
			if (obj_label!=null) {
				list = obj_label.getImages();
			}
		} else if (StringUtils.isNotEmpty(keyword)) {
			String _keyword = URLDecoder.decode(keyword, "UTF-8");
			Label obj_label = labelService.searchLabel(_keyword);
			if (obj_label!=null) {
				list = obj_label.getImages();
			}
		}
		
		for(Image l:list) {
//			String p = URLEncoder.encode(l.getPath(), "UTF-8");
			String bp = l.getBucket().getPath().replace("\\", "/");
			l.getBucket().setPath(bp);
			String cp = l.getCamera().getPath().replace("\\", "/");
			l.getCamera().setPath(cp);
			String p = l.getPath().replace("\\", "/");
			l.setPath(p);
			String c = l.getPath().replace("\\", "/");
			l.setCache(c); 
		}
		
		model.put("list", list);
		model.put("dates", dates);
		
		return "image/list";
	}
	
	private Set<String> getDates(List<Image> list){
		Set<String> dates = new TreeSet<String>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		for (Image i:list) {
			dates.add(sdf.format(i.getTime()));
		}
		return dates;
	}
}
